<template>
  <div class="song-audio">
    <audio
      id="player"
      controls="controls"
      preload="true"
      :src="url"
      @canplay="startPlay"
      @ended="ended"
    ></audio>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      src: "http://localhost:1109/song/1649597760863可爱女人.mp3",
    };
  },
  name: "song-audio",
  computed: {
    ...mapGetters([
      "id",
      "url", // 音乐链接
      "isPlay", // 播放状态
    ]),
  },
  watch: {
    // 监听播放还是暂停
    isPlay: function () {
      this.togglePlay();
    },
  },
  methods: {
    // 获取歌曲链接后准备播放
    startPlay() {
      let player = document.querySelector("#player");
      player.play();
    },
    // 开始/暂停
    togglePlay() {
      let player = document.querySelector("#player");
      if(this.isPlay){
          player.play();
      }else{
          player.pause();
      }
    },
    // 音乐播放结束时触发
    ended() {
      this.isPlay = false;
    },
  },
};
</script>

<style>
audio  {
  display: none;
}
</style>